package org.jeecg.common.util;

import cn.hutool.crypto.SecureUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

/**
 * (概要说明).
 *
 * @author chao.xie
 * @version 1.0.0
 * @创建日期: 2024.03.26
 */
public class SignUtil {
    /**
     * 数据签名.
     *
     * @author chao.xie
     * @创建日期: 2024.03.26
     * @param map 签名数据
     * @param key 签名key
     * @return java.lang.String
     * @since 1.0.0
     */
    public static String getSign(Map<String,Object> map, String key){
        return getSign(map, key, new String[]{});
    }

    /**
     * 数据签名.
     *
     * @author chao.xie
     * @创建日期: 2024.03.26
     * @param map 签名数据
     * @param key 签名key
     * @param ignoreProperty 不参与签名的对象属性
     * @return java.lang.String
     * @since 1.0.0
     */
    public static String getSign(Map<String,Object> map, String key, String... ignoreProperty){
        map.remove("sign");
        for(String prop : ignoreProperty){
            map.remove(prop);
        }

        ArrayList<String> list = new ArrayList<String>();
        for(Map.Entry<String,Object> entry:map.entrySet()){
            if(null != entry.getValue()
                    && !"".equals(entry.getValue())
                    && !(entry.getValue() instanceof Collection)){
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String [] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + key;
        SecureUtil.md5(result).toUpperCase();
        result = SecureUtil.md5(result).toUpperCase();
        return result;
    }
}
